package yiran.itemuse.data;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import yiran.itemuse.ConfigManager;
import yiran.itemuse.output.Logger;

public class DatabaseService {
    private static Connection connection;

    public static Connection getConnection() throws SQLException {
        if (connection == null || connection.isClosed()) {
            String dbType = ConfigManager.getDatabaseType();

            if ("sqlite".equalsIgnoreCase(dbType)) {
                String dbFile = ConfigManager.getSQLitePath();
                connection = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
            }
            else if ("mysql".equalsIgnoreCase(dbType)) {
                String url = "jdbc:mysql://" +
                        ConfigManager.getMySQLHost() + ":" +
                        ConfigManager.getMySQLPort() + "/" +
                        ConfigManager.getMySQLDatabase();
                connection = DriverManager.getConnection(url,
                        ConfigManager.getMySQLUser(),
                        ConfigManager.getMySQLPassword());
            }
        }
        return connection;
    }

    public static void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                Logger.error("关闭数据库连接失败: " + e.getMessage());
            }
        }
    }

    public static void initializeDatabase() {
        String dbPath = ConfigManager.getSQLitePath();
        File dbFile = new File(dbPath);

        if (!dbFile.exists()) {
            try {
                File parentDir = dbFile.getParentFile();
                if (parentDir != null && !parentDir.exists()) {
                    parentDir.mkdirs();
                }

                dbFile.createNewFile();
            } catch (IOException e) {
                Logger.error("无法创建数据库文件: " + e.getMessage());
                return;
            }
        }

        String createTableSQL = "CREATE TABLE IF NOT EXISTS item_commands (" +
                "item_key TEXT PRIMARY KEY," +
                "command TEXT NOT NULL," +
                "consume BOOLEAN NOT NULL)";

        try (Connection conn = DatabaseService.getConnection();
             Statement stmt = conn.createStatement()) {

            stmt.execute(createTableSQL);
            Logger.info("数据库初始化成功: " + dbFile.getName());

        } catch (SQLException e) {
            Logger.error("数据库初始化失败: " + e.getMessage());
        }
    }
}
